import { Provide } from '@midwayjs/decorator';
// import { BaseService } from 'midwayjs-cool-core';

import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { loeeBaseService } from '../../../comservice/loeeBaseService';
import { studentEntity } from '../../student/entity/student';
import { classTeachingEntity } from '../entity/classTeaching';
import { studentClassDetailEntity } from '../entity/studentClassDetail';

/**
 * 描述
 */
@Provide()
export class classTeachingService extends loeeBaseService {

  @InjectEntityModel(classTeachingEntity)
  classTeachingEntity: Repository<classTeachingEntity>;

  @InjectEntityModel(studentClassDetailEntity)
  studentClassDetailEntity: Repository<studentClassDetailEntity>;

  /**
   * 重写新增接口
   */
  async add(param: any) {
    console.log(param, '22222222222');
    // student_id
    // classgroup_id
    const classTeachingObj: any = await super.add(param);
    console.log(classTeachingObj, 1111111111);
    let class_students = param.class_students

    if (class_students) {
      // 遍历列表
      for (let item of class_students) {
        await this.studentClassDetailEntity.save({
          class_teaching: classTeachingObj.id,
          student: item.student,
          common_use_num: item.common_use_num,
          special_use_num: item.special_use_num,
          isPlacement: item.isPlacement,
          isLeave: item.isLeave,
          rate: item.rate,
          comments: item.comments,
          note: item.note,
        })
      }
    }
    return {
      id: param.id
    }
  }

  /**
     * 重写info接口
     * @param id ID
     * @param infoIgnoreProperty 忽略返回属性
     */
  async info(id, infoIgnoreProperty) {
    const classTeachingObj = await super.info(id, infoIgnoreProperty);
    console.log(classTeachingObj, 1010101010);

    // const studentClassDetailObj = await this.studentClassDetailEntity.find({class_teaching:classTeachingObj.id})
    const studentClassDetailObj = await this.getAllUsers(classTeachingObj)
    console.log(classTeachingObj, 1111);
    // console.log(studentClassDetailObj, 2222);
    classTeachingObj.class_students = studentClassDetailObj
    console.log(classTeachingObj, 33333333);

    return classTeachingObj
  }

  /**
     * 重写修改
     * @param param 数据
     */
  async update(param) {
    await super.update(param);
    await this.studentClassDetailEntity.delete({ class_teaching: param.id });
    let class_students = param.class_students

    if (class_students) {
      // 遍历列表
      for (let item of class_students) {
        await this.studentClassDetailEntity.save({
          class_teaching: param.id,
          student: item.student,
          common_use_num: item.common_use_num,
          special_use_num: item.special_use_num,
          isPlacement: item.isPlacement,
          isLeave: item.isLeave,
          rate: item.rate,
          comments: item.comments,
          note: item.note,
        })
      }
    }

  }

  /**
     * 重写分页查询
     * @param query
     */
  async page(query) {
    console.log(query, '+++++++++');

    const { keyWord, teacher, class_date, student,teaching_class,class_type } = query;
    console.log(typeof (class_date), '++++');

    let start_date = 1900 - 1 - 1
    let end_date = 2999 - 1 - 1
    if (class_date !== null && class_date !== undefined) {
      start_date = class_date[0].slice(0, 10)
      end_date = class_date[1].slice(0, 10)
    }

    console.log("this is query------------------------------", query);
    // query.order = 'sort'
    // query.sort = 'asc'
    // const permsDepartmentArr = await this.baseSysPermsService.departmentIds(
    //   this.ctx.admin.userId
    // ); // 部门权限
    const sql = `
      SELECT
          a.id,a.teaching_semester,a.course_type,a.section_theme,e.section_theme as section_theme_name,a.teacher,a.class_date,a.teaching_class,a.note,a.createTime,a.updateTime,a.isDelete,
          GROUP_CONCAT(b.isPlacement,c.name,':',c.student_id) AS class_students
      FROM
          class_teaching a
          LEFT JOIN student_class_detail b ON a.id = b.class_teaching
          LEFT JOIN student c ON b.student = c.id
          LEFT JOIN teacher d ON a.teacher = d.id
          LEFT JOIN course_source e ON a.section_theme = e.id

      WHERE 1 = 1 and a.isDelete = false and b.isLeave = false
      ${this.setSql(teacher, 'and d.id = ?', [teacher])}
      ${this.setSql(student, 'and c.id = ?', [student])}
      ${this.setSql(teaching_class, 'and a.teaching_class = ?', [teaching_class])}
      ${this.setSql(class_type, 'and a.class_type = ?', [class_type])}
      
      ${this.setSql(class_date, 'and a.class_date >= ? and a.class_date <= ?', [start_date, end_date])}
      ${this.setSql(keyWord, 'and (e.section_theme LIKE ? or c.name LIKE ? or c.student_id LIKE ?)', [
      `%${keyWord}%`,
      `%${keyWord}%`,
      `%${keyWord}%`,
    ])}
      GROUP BY a.id
      order by a.class_date desc
      `;
    return this.sqlRenderPage(sql, query, true);
  }

  /**
     * 执行SQL并获得分页数据
     * @param sql 执行的sql语句
     * @param query 分页查询条件
     * @param autoSort 是否自动排序
     * @param connectionName 连接名称
     */
   async sqlRenderList(sql, query) {
    
    let params = [];
    params = params.concat(this.sqlParams);
    const result = await this.nativeQuery(sql, params);
    return result
}


  /**
     * 重写list
     * @param query 查询条件
     * @param option 查询配置
     */
  async list(query, option) {
    console.log(option);
    
    const { keyWord,student_id } = query;
    
    const sql = `
      SELECT
          a.id,a.student,a.class_teaching,a.common_use_num,a.special_use_num,a.use_type,a.isLeave,a.isPlacement,a.rate,a.comments,a.note,a.createTime,a.updateTime,a.isDelete,
          c.section_theme,b.teacher,b.class_date,b.teaching_semester,d.name as teacherName,e.phase_name,GROUP_CONCAT(f.class_date,f.class_name,f.class_number) as classgroup,c.learning_goals
      FROM
          student_class_detail a
          LEFT JOIN class_teaching  b ON a.class_teaching = b.id
          LEFT JOIN course_source c ON b.section_theme = c.id
          LEFT JOIN teacher d ON b.teacher = d.id
          LEFT JOIN course_system e ON c.phase_name = e.id
          LEFT JOIN classgroup f ON b.teaching_class = f.id

      WHERE 1 = 1 and a.isDelete = false and a.isLeave = false
      ${this.setSql(student_id, 'and a.student = ?', [student_id])}
      ${this.setSql(keyWord, 'and (a.section_theme LIKE ? or d.name LIKE ? or c.scientific LIKE ?)', [
      `%${keyWord}%`,
      `%${keyWord}%`,
      `%${keyWord}%`,
    ])}
      GROUP BY a.id
      `;
    
    return this.sqlRenderList(sql, query);
  }

  getAllUsers(obj) {

    return this.studentClassDetailEntity.createQueryBuilder()
      .leftJoinAndSelect(studentEntity, 'b', 'student = b.id')
      .select(`
        class_teaching,
        comments,
        common_use_num,
        isLeave,
        isPlacement,
        rate,
        special_use_num,
        student,
        studentClassDetailEntity.note as note,
        b.name as name
      `)
      .where("class_teaching = :id", { id: obj.id })
      // .select(`
      //   article.id as id,
      //   article.title as title,
      //   article.content as content,
      //   user.id as userId,
      //   user.nickname as nickname,
      //   user.username as usernmae,
      //   user.avator as avator
      // `)
      .getRawMany();
  }
  /**
   * 重写删除方法删除班级扣课的同时应该删除学生的上课记录
   */
   async delete(ids:any) {
    await super.delete(ids)
    let idsArray: Array<number> 
    if (ids instanceof Array) {
      idsArray = ids
    }else{
      idsArray = ids.split(",")
    }
    for (let id of idsArray) {
      await this.studentClassDetailEntity.delete({ class_teaching: id });
    }
    await this.modifyAfter(ids,'delete');
  }

}



